package com.shycloud.mido.task.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joy.zebra.common.push.JPushUtils;
import com.shycloud.mido.common.core.constant.CommonConstants;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.homework.api.enums.JPushCodeEnum;
import com.shycloud.mido.member.api.entity.Member;
import com.shycloud.mido.member.api.entity.MemberRole;
import com.shycloud.mido.member.api.entity.MsgMain;
import com.shycloud.mido.member.api.entity.MsgMemberInfo;
import com.shycloud.mido.member.api.feign.RemotePushService;
import com.shycloud.mido.member.api.util.Constant;
import com.shycloud.mido.task.api.entity.SmMemberTask;
import com.shycloud.mido.task.api.entity.SmMemberTaskComplete;
import com.shycloud.mido.task.mapper.*;
import com.shycloud.mido.task.service.SmMemberTaskCompleteService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
@AllArgsConstructor
public class SmMemberTaskCompleteServiceImpl extends
		ServiceImpl<SmMemberTaskCompleteMapper, SmMemberTaskComplete> implements
		SmMemberTaskCompleteService {

	/** 任务模块 mapper */
	private final SmMemberTaskMapper taskMapper;
	/** 任务完成情况 mapper */
	private final SmMemberTaskCompleteMapper taskCompleteMapper;
	/** 会员模块 mapper */
	private final MemberRoleMapper memberRoleMapper;
	/** 用户模块 mapper */
	private final MemberMapper memberMapper;
	/** 消息发送 */
	private final RemotePushService pushService;
	/** 通知模块 mapper */
	private final SmMemberNoticeMapper noticeMapper;

	/**
	 * 完成任务领取奖励
	 *
	 * @param taskId
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/27 14:54
	 **/
	@Override
	@Transactional(rollbackFor = Exception.class, timeout = 36000)
	public Boolean receiveAward(Integer taskId, String memberId, String excStr) {

		if (memberId == null) {
			memberId = SecurityUtils.getMember().getId();
		}

		//分享注册活动分享者无限制领取
		if (taskId != 6 && taskId != 9) {
			if (taskCompleteMapper.selectOne(
					new QueryWrapper<SmMemberTaskComplete>().eq("task_id", taskId)
							.eq("member_id", memberId)) != null) {
				throw new BusinessException("您已经领取过该奖励了，无需再次领取");
			}
		}

		//获取任务信息
		SmMemberTask smMemberTask = taskMapper.selectById(taskId);

		return receiveAwardTask(smMemberTask, memberId, excStr);
	}

	/**
	 * 领取任务奖励
	 *
	 * @param smMemberTask
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/27 15:25
	 **/
	private Boolean receiveAwardTask(SmMemberTask smMemberTask, String memberId, String excStr) {

		Member member = memberMapper.selectById(memberId);

		//奖励类型为 VIP
		if ("1".equals(smMemberTask.getRewardType())) {

			//充值 or 续费会员
			MemberRole role = memberRoleMapper.selectOne(new QueryWrapper<MemberRole>()
					.eq("member_id", memberId)
					.and(x -> x.eq("role_code", Constant.VIP_MEMBER)));

			if (role != null) {

				//创建时间
				role.setCreateTime(LocalDateTime.now());

				//如果还没到期，那么从到期时间开始累加
				if (role.getEndTime().isAfter(LocalDateTime.now())) {

					if ("天".equals(smMemberTask.getUnit())) {
						role.setEndTime(role.getEndTime().plusDays(smMemberTask.getReward()));
					}

					if ("个月".equals(smMemberTask.getUnit())) {
						role.setEndTime(role.getEndTime().plusMonths(smMemberTask.getReward()));
					}

				}
				//如果已经到期，那么从今天开始累加会员天数
				else {
					role.setStartTime(LocalDateTime.now());

					if ("天".equals(smMemberTask.getUnit())) {
						role.setEndTime(LocalDateTime.now().plusDays(smMemberTask.getReward()));
					}

					if ("个月".equals(smMemberTask.getUnit())) {
						role.setEndTime(LocalDateTime.now().plusMonths(smMemberTask.getReward()));
					}
				}
				memberRoleMapper.updMemberRole(role);
			} else {
				//新增会员
				role = new MemberRole();
				//创建时间
				role.setCreateTime(LocalDateTime.now());
				//开始时间
				role.setStartTime(LocalDateTime.now());
				//结束时间
				if ("天".equals(smMemberTask.getUnit())) {
					role.setEndTime(LocalDateTime.now().plusDays(smMemberTask.getReward()));
				}
				if ("个月".equals(smMemberTask.getUnit())) {
					role.setEndTime(LocalDateTime.now().plusMonths(smMemberTask.getReward()));
				}
				//会员
				role.setRoleCode(Constant.VIP_MEMBER);
				role.setDelFlag("0");
				//用户ID
				role.setMemberId(memberId);
				memberRoleMapper.saveMemberRole(role);
			}
		}

		//TODO 奖励类型为积分
		if ("2".equals(smMemberTask.getRewardType())) {
		}
		//TODO 奖励类型为经验值
		if ("3".equals(smMemberTask.getRewardType())) {
		}
		//奖励类型 为虚拟币
		if ("4".equals(smMemberTask.getRewardType())) {
			//获取奖励数量
			Integer goldCount = smMemberTask.getReward();
			member.setGold(member.getGold() + goldCount);
			memberMapper.updateById(member);
		}

		//奖励类型 特殊活动赠送在线课
		if (StringUtils.equals("5", smMemberTask.getRewardType())) {
			//此处用到扩展字符串 excStr 以“_”形式分割 第一位是 orgId 第二位是 count
			String[] excStrArr = excStr.split("_");
			Integer onlineCount = Integer.parseInt(excStrArr[1]) * Integer.parseInt(smMemberTask.getUnit());
			return noticeMapper.addOnlineCourse(Integer.parseInt(excStrArr[0]), onlineCount) == 1;
		}

		// 新增消息
		String rewardType = getRewardTypeStr(smMemberTask);

		String msgId = addMsg("活动奖励",
				"您已获得" + smMemberTask.getReward() + smMemberTask.getUnit() + rewardType
						+ "奖励,请在个人设置页面查看");
		// 发送消息
		MsgMemberInfo msgMemberInfo = new MsgMemberInfo();
		msgMemberInfo.setMsgId(msgId);
		msgMemberInfo.setFromId("sys");
		msgMemberInfo.setToId(memberId);
		msgMemberInfo.setCreateTime(LocalDateTime.now());
		msgMemberInfo.setDelFlag(CommonConstants.STATUS_NORMAL);
		pushService.sendMsg(msgMemberInfo);

		if (member != null) {
			JPushUtils.sendJPush("活动奖励", "您已获得" + smMemberTask.getReward() + smMemberTask.getUnit() + rewardType
					+ "奖励,请在个人设置页面查看", member.getClientId());

			JPushUtils.sendJMessage(JPushCodeEnum.J_PUSH_APP_HOMEPAGE_VIEW.getType(), member.getClientId(), "请求 getMsgApp 接口");
		}

		//记录此人已经完成了这个任务
		return taskComplate(memberId, smMemberTask.getId());

	}

	private Boolean taskComplate(String memberId, Integer taskId) {

		SmMemberTaskComplete taskComplete = new SmMemberTaskComplete();

		taskComplete.setMemberId(memberId);

		taskComplete.setTaskId(taskId);

		return taskCompleteMapper.insert(taskComplete) == 1;
	}

	private String getRewardTypeStr(SmMemberTask task) {

		String rewardType = StringUtils.EMPTY;

		if ("1".equals(task.getRewardType())) {
			rewardType = "VIP会员时长";
		}
		if ("4".equals(task.getRewardType())) {
			rewardType = "快乐贝";
		}
		return rewardType;
	}

	private String addMsg(String title, String message) {

		MsgMain msgMain = new MsgMain();
		//给教师或者学生发送
		msgMain.setTriggerTo("4");
		//来自分享注册活动奖励通知 - 系统自动推送
		msgMain.setTriggerFrom("0");
		//消息下发的场合：活动奖励领取
		msgMain.setPoint("7");
		//不可修改
		msgMain.setModify("0");
		//自动推送
		msgMain.setMode("1");
		//个人
		msgMain.setRangeType("1");
		//有效数据
		msgMain.setDelFlag("0");
		//创建时间
		msgMain.setCreateTime(LocalDateTime.now());
		//消息类型：文本
		msgMain.setMsgType("0");
		//发送时间
		msgMain.setActualPubDatetime(LocalDateTime.now());
		//创建人-> 系统
		msgMain.setCreateUser("sys");
		//消息内容
		msgMain.setMessage(message);
		//发布时间
		msgMain.setPubDatetime(LocalDateTime.now());
		//推送成功
		msgMain.setPushStatus("0");
		//推送时间
		msgMain.setPushTime(LocalDateTime.now());
		//标题
		msgMain.setTitle(title);
		//系统消息
		msgMain.setType("0");

		return (String) pushService.addMsg(msgMain).getData();
	}

}
